package com.fnd.med.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.fnd.med.zsms.bean.Operation;

public class SyncUtil {
	public static Map<String, List<Integer>> getOpMap(List<Operation> operations) {
		if ((operations == null) || (operations.isEmpty())) {
			return new HashMap<String, List<Integer>>();
		}

		Collections.sort(operations, new java.util.Comparator<Operation>() {
			public int compare(Operation o1, Operation o2) {
				return o1.getServerSeq() - o2.getServerSeq() > 0 ? 1 : -1;
			}

		});

		Map<Integer, Operation> map1 = new HashMap<Integer, Operation>();
		Iterator<Operation> it1 = operations.iterator();
		while (it1.hasNext()) {
			Operation op1 = it1.next();
			Operation op0 = map1.get(Integer.valueOf(op1.getDataSeq()));
			if (op0 == null) {
				map1.put(Integer.valueOf(op1.getDataSeq()), op1);
			} else {
				if ((op0.getOpType().equals("100")) && (op1.getOpType().equals("300"))) {
					map1.remove(Long.valueOf(op1.getServerSeq()));
				}

				if ((op0.getOpType().equals("200")) && (op1.getOpType().equals("300"))) {
					map1.put(Integer.valueOf(op1.getDataSeq()), op1);
				}
			}
		}

		Collection<Operation> operations2 = map1.values();
		Iterator<Operation> it2 = operations2.iterator();

		List<Integer> inserts = new ArrayList<Integer>();
		List<Integer> updates = new ArrayList<Integer>();
		List<Integer> deletes = new ArrayList<Integer>();
		while (it2.hasNext()) {
			Operation op = (Operation) it2.next();
			if (op.getOpType().equals("300"))
				deletes.add(Integer.valueOf(op.getDataSeq()));

			if (op.getOpType().equals("100"))
				inserts.add(Integer.valueOf(op.getDataSeq()));

			if (op.getOpType().equals("200"))
				updates.add(Integer.valueOf(op.getDataSeq()));
		}

		Map<String,List<Integer>> map2 = new HashMap<String,List<Integer>>();
		map2.put("100", inserts);
		map2.put("200", updates);
		map2.put("300", deletes);
		return map2;
	}
}